package com.xiaodou.mjf.web.xface.product.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.manager.ProductManager;
import com.xiaodou.mjf.application.core.service.FinancialPackageService;
import com.xiaodou.mjf.application.core.service.FinancingAttributeService;
import com.xiaodou.mjf.application.core.service.FinancingService;
import com.xiaodou.mjf.application.core.service.FinancingStatisticsService;
import com.xiaodou.mjf.application.core.service.InvestService;
import com.xiaodou.mjf.application.user.service.MemberService;
import com.xiaodou.mjf.entity.core.FinancialPackage;
import com.xiaodou.mjf.entity.core.Financing;
import com.xiaodou.mjf.entity.core.FinancingAttribute;
import com.xiaodou.mjf.entity.core.FinancingStatistics;
import com.xiaodou.mjf.entity.core.Invest;
import com.xiaodou.mjf.entity.user.Member;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.ResultCode;

/**
 * Created by Rocky on 2/27/15.
 */
@RestController
@RequestMapping("v1/product")
public class ProductController extends ApiController {

	@Resource
	FinancingService financingService;
	@Resource
	FinancialPackageService financialPackageService;
	@Resource
	MemberService memberService;
	@Resource
	FinancingAttributeService financingAttributeService;
	@Resource
	InvestService investService;
	@Resource
	FinancingStatisticsService financingStatisticsService;
	
	@Resource
	ProductManager productManager;
	//剩余数量0 
	public static final Integer RESIDUAL_COUNT_EMPTY=0;
	//剩余金额0
	public static final Double RESIDUAL_AMOUNT_EMPTY=0D;
	
	
	/**
	 * 提交购买信息
	 * @param id
	 * @param uid
	 * @param name
	 * @param amount
	 * @param type
	 * @return result
	 */
    @RequestMapping("{id}/purchase")
	public Map<String, Object> purchase(@PathVariable String id,
			@RequestHeader(required = false) String uid, 
			Double amount, Integer type) {

		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		if (StringUtils.isBlank(id) || type == null) {
			return failure(ResultCode.MISSING_PARAMS);
		}

		// 判断用户是否存在
		Member member = memberService.get(uid);

		if (member == null) {
			return failure(ResultCode.USER_NOT_EXIST);
		}

		Financing financing = new Financing();
		FinancialPackage financialPackage = new FinancialPackage();
		FinancingStatistics financingStatistics = new FinancingStatistics();
		double expectedProfit = 0D;
		// 美丽
		if (Financing.TYPE_MEILI.equals(type)) {

			// 如果是美丽，直接查找financing表的记当前对应id的记录
			financing = financingService.get(id);
			//如果用户含有相同产品的订单，则不能提交购买
			List<Invest> investList = investService.findForNotPayment(financing.getId(), uid, 1);
			if(investList.size()>0){
				return failure(ResultCode.HAS_INVEST_UNPAYMENT);
			}
			// 从financing_attribute表获取预期收益
			FinancingAttribute financingAttribute = financingAttributeService
					.get(id);
			// 根据finance_id更新financing_statistics表
			financingStatistics = financingStatisticsService
					.findByfinanceId(financing.getId());
			//根据剩余数量判断 如果为0 提示错误信息 
			//add by David 2015/04/13  start
			if(RESIDUAL_COUNT_EMPTY.equals(financingStatistics.getResidualCount())){
				return failure(ResultCode.RESIDUAL_COUNT_LACK);
			}
			//add by David 2015/04/13 end
			if (financingAttribute != null) {
				expectedProfit = financingAttribute.getRefundAmount().doubleValue();
			}
			financingStatistics.setCount(financingStatistics.getCount().intValue() + 1);
			financingStatistics.setResidualCount(financingStatistics
					.getResidualCount().intValue() - 1);
		}
		// 小豆
		else if (Financing.TYPE_XIAODOU.equals(type) ) {
			if ( amount == null || type == null) {
				return failure(ResultCode.MISSING_PARAMS);
			}
			// 如果是小豆，根据financial_package查处的term再查financing表中term相同并且invest_status=0（售卖中）的记录
			financialPackage = financialPackageService.get(id);
			// 如果购买金额 小于financialPackage中最小购买金额 返回提示错误
			if (amount < financialPackage.getMinAmount().doubleValue()) {
				return failure(ResultCode.INVALID_PURCHASEAMOUNT);
			}
			financing = financingService.getFinancingByTermAndInvsetStatus(
					financialPackage.getTerm().intValue(), Financing.INVEST_STATUS_SALE.intValue(),Financing.TYPE_XIAODOU);			
			if(financing==null){
				return failure(ResultCode.RECORD_NOT_EXIST);
			}
			//如果用户含有相同产品的订单，则不能提交购买
			List<Invest> investList = investService.findForNotPaymentXiaodou(financing.getId(), uid, 1, amount);
			if(investList.size()>0){
				return failure(ResultCode.HAS_INVEST_UNPAYMENT);
			}
			// 计算预期收益 add by David 2015/04/15 start
			try {
				expectedProfit = amount.doubleValue()*financing.getMinProfitRate().doubleValue() / 100 / 12* financialPackage.getTerm().intValue();
				//add by David 2015/04/15 end
			} catch (Exception e) {
				logger.error(e.toString());
				return failure(ResultCode.EXPECTEDPROFIT_ERROR);
			}

			// 根据finance_id更新financing_statistics表
			financingStatistics = financingStatisticsService
					.findByfinanceId(financing.getId());
			financingStatistics.setCount(financingStatistics.getCount()==null?0:financingStatistics.getCount().intValue() + 1);
			//根据金额判断 如果为0 提示错误信息 
			if(RESIDUAL_AMOUNT_EMPTY.equals(financingStatistics.getResidualAmount())){
				return failure(ResultCode.RESIDUAL_AMOUNT_LACK);
			}
			financingStatistics.setResidualAmount(financingStatistics
					.getResidualAmount().doubleValue() - amount);
		} else {
			return failure(ResultCode.INVALID_TYPE);
		}
		// 把查出来的记录插入invest表
		Invest invest = new Invest();
		invest.setFinanceId(financing.getId());
		invest.setMemberId(uid);
		invest.setMemberName(member.getRealName());
		invest.setType(type);
		invest.setCount(Invest.INIT_COUNT);
		invest.setAmount(amount);
		invest.setInvestDate(DateUtils.getCurrentTime());
		invest.setTerm(financing.getTerm());
		invest.setStatus(Invest.NORMAL);
		//设置付款状态 未付款
		invest.setPaymentStatus(Invest.INVEST_NON_PAYMENT);
		invest.setEarnedProfit(0D);
		invest.setExpectedProfit(expectedProfit);
		// TODO
		invest.setChannelId("100210001");
		try {
			
//			investService.save(invest);
//			// 提交更新
//			financingStatisticsService.save(financingStatistics);
			productManager.purchase(financingStatistics, invest);
			Map<String,Object> result = success();
			// result.put("tn",String.valueOf(System.currentTimeMillis()+
			// RandomUtils.nextLong(111111, 999999)));
			result.put("tn", invest.getId());
			return result;
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.PURCHASE_ERROR);
		}
        
    }
    
}
